
import { NewAppScreen } from '@react-native/new-app-screen';
import React, { useState, useEffect } from 'react';
import { TouchableOpacity, Dimensions, StatusBar, StyleSheet, useColorScheme, Text, View, Alert } from 'react-native';

import { WebView } from 'react-native-webview';
import Geolocation from 'react-native-geolocation-service';

import {
  checkLocation,
  requestLocation
} from './utils/lib/Permission';
import { openSettings, RESULTS } from 'react-native-permissions';

import { socket } from './utils/lib/Socket';
// import { savePlayerLocaDataService } from './api/fetch';

import Storage from 'react-native-storage';
import uuid from 'react-native-uuid';

import proxy from './config/host'
import axios from 'axios';



let playerLocaQueueTimer: string | number | NodeJS.Timeout | undefined;
class CreateTimerExecuteLock {
  static instance: any;
  static timer(uuid: string, time: number) {
    playerLocaQueueTimer = setInterval(async () => {

      const loca: any = await getLocation();

      const data: playerInfo = {
        playerName: 'Test Player',
        playerUID: uuid,
        /**@description {pro} */
        playerLong: loca.coords.longitude,
        playerLat: loca.coords.latitude,
        /**@description {dev} */
        // playerLong: null,
        // playerLat: null,
        playerDirection: loca.coords.heading,
        playerSpeed: loca.coords.speed,
        locaType: 'GPS'
      };

      socket.emit('IO_ROOM_PLAYERS_INFO_TIMER', data);

    }, time);
  };

  static main(uuid: string, time: number) {
    if (!CreateTimerExecuteLock.instance) {
      CreateTimerExecuteLock.instance = new CreateTimerExecuteLock();
      CreateTimerExecuteLock.timer(uuid, time);
    };
    return CreateTimerExecuteLock.instance;
  };
};



interface playerInfo {
  playerName: string,
  playerUID: string,
  playerLong: number,
  playerLat: number,
  playerDirection: number,
  playerSpeed: number,
  locaType: string
};



let loca: any;


const storage = new Storage({
  size: 1000,
  // defaultExpires: 1000 * 3600 * 24,  // 1 day
  defaultExpires: null,
  enableCache: true
});


const player_uuid_init = () => {
  return new Promise((resolve, reject) => {
    storage.save({
      key: 'uuid',
      data: uuid.v4(),
      expires: null
    });
    resolve(1);
  });
};


const savePlayerStatusDataService = (status: Object) => {
  return new Promise((resolve, reject) => {
    axios.post(`${proxy.development.API}/api/v1/temp_api/game/savePlayerStatusDataService`, status)
      .then(response => {
        if (response.data.code == 200) {
          resolve(1);
        };
      })
      .catch(error => {
        reject(error);
      });
  });
};

const socketInit = () => {
  socket.on('connect', async () => {
    console.log('socket connect!');
    if (CreateTimerExecuteLock.instance) delete CreateTimerExecuteLock.instance;

    /**@description join game world */
    socket.emit('IO_ROOM_JOIN_GAME_WORLD', 'JOIN');

    showActionSheet();
  });
  socket.on('disconnect', () => {
    console.log('socket disconnect!');

    clearInterval(playerLocaQueueTimer);
    if (CreateTimerExecuteLock.instance) delete CreateTimerExecuteLock.instance;
  });

  /**@description all listen events */
  socket.on('IO_ROOM_PLAYERS_READY_START_GAME_DATA', async puid => {

    /**@description {pro} */
    const uuid = await storage.load({
      key: 'uuid',
      autoSync: true,
      syncInBackground: true
    });

    if (puid === uuid) {
      io_room_start_Game(uuid);
    };

  });
};



const io_room_start_Game = async (uuid: string) => {

  socket.emit('IO_ROOM_PLAYERS_START_GAME', uuid);

  CreateTimerExecuteLock.main(uuid, 5000);

};


const showActionSheet = async () => {
  // 定位
  const isLocation = checkLocation;
  if (isLocation) {
    const status = await requestLocation?.();

    if (status === RESULTS.GRANTED) {
      console.log('定位权限已授予');
    } else {
      console.log('用户拒绝权限');
      showAlertPermission();
    };
  } else {
    showAlertPermission();
  };
};

const getLocation = () => {
  return new Promise((resolve, reject) => {
    Geolocation.getCurrentPosition(
      (position) => {
        resolve(position);
      },
      (error) => {
        reject({ code: error.code, msg: error.message });
      },
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
  })
};

const showAlertPermission = () => {
  Alert.alert('提示', '权限获取失败,请打开设置允许相关权限', [
    {
      text: '确认', onPress: () => {
        openSettings().then().catch();
      }
    },
    { text: '取消', style: 'cancel' }
  ], { cancelable: false });
};

let uid: string;
let url: string;
const startGame = async () => {

  try {
    await player_uuid_init();

    const uuid = await storage.load({
      key: 'uuid',
      autoSync: true,
      syncInBackground: true
    });

    uid = uuid;

    loca = await getLocation();

    const info = await axios.get(`${proxy.development.API}/api/v1/temp_api/game/getPlayerInitInfoDev`);

    const data = info.data.message.playerInfo.data;
    /**@description {pro} */
    data.playerLong = loca.coords.longitude;
    data.playerLat = loca.coords.latitude;

    data.playerDirection = loca.coords.heading;
    data.playerSpeed = loca.coords.speed;
    data.playerUID = uuid;

    const building = info.data.message.playerInfo.building;
    /**@description {pro} */
    building.playerUID = uuid;

    const industry = info.data.message.playerInfo.industry;
    /**@description {pro} */
    industry.playerUID = uuid;

    const food = info.data.message.playerInfo.food;
    /**@description {pro} */
    food.playerUID = uuid;

    const response_status = await savePlayerStatusDataService({
      playerName: 'Test Player',
      playerUID: uuid,
      cronJob: {
        uiStatus: {
          falloutProgress: 100,
          sodaProgress: 100,
          stomach: 100
        }
      }
    });

    const response_industry = await axios.post(`${proxy.development.API}/api/v1/temp_api/game/playersIndustryStatus`, industry);

    const response_building = await axios.post(`${proxy.development.API}/api/v1/temp_api/game/playersBuildingStatus`, building);

    const response_food = await axios.post(`${proxy.development.API}/api/v1/temp_api/game/playersFoodStatus`, food);

    if (response_industry.data.code == 200 && response_building.data.code == 200 && response_food.data.code == 200) {
      axios.post(`${proxy.development.API}/api/v1/temp_api/game/savePlayersInfoForFirst`, data)
        .then(response => {
          if (response.data.code == 200) {
            /**@description {pro} */
            url = `${proxy.development.WEB_VIEW_API}?playerUID=${uuid}`;
            /**@description {dev} */
            // url = '';

            vv();
          };
        })
        .catch(error => {
          console.log(error);
        });
    };

  } catch (error) {
    console.log(error);
  };

};

const loadGame = async () => {
  return;
  const uuid = await storage.load({
    key: 'uuid',
    autoSync: true,
    syncInBackground: true
  });

  uid = uuid;

  vv();
};



let vv: () => void;
function App() {
  // const isDarkMode = useColorScheme() === 'dark';

  const [isVisible, setIsVisible] = useState(true);

  useEffect(() => {
    socketInit();

    return () => {
      console.log('组件正在卸载，执行清理操作');

      if (socket && socket.connected) {
        socket.disconnect();
      };

    };
  }, []);

  vv = () => {
    setIsVisible(!isVisible);
  };

  return (
    <View style={styles.container}>

      {/* <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} /> */}
      {/* <NewAppScreen templateFileName="App.tsx" /> */}

      {isVisible &&
        (<View style={styles.ui_container}>
          <TouchableOpacity onPress={startGame} style={[styles.ui_button, styles.ui_start_button]}>
            <Text style={{ color: '#424040ff', fontSize: 32, fontWeight: 'bold', textShadowColor: 'rgba(217, 198, 198, 1)', textShadowOffset: { width: 0, height: 2 }, textShadowRadius: 3 }}>
              开始游戏
            </Text>
          </TouchableOpacity>

          <TouchableOpacity onPress={loadGame} style={[styles.ui_button, styles.ui_load_button]}>
            <Text style={{ color: '#b4afafff', fontSize: 22, fontWeight: 'bold', textShadowColor: '#d3cdcdff', textShadowOffset: { width: 0, height: 2 }, textShadowRadius: 3 }}>
              读取游戏
            </Text>
          </TouchableOpacity>
        </View>)
      }

      {!isVisible &&
        (<WebView
          source={{
            uri: url
          }}
          style={{
            flex: 1
          }}
          originWhitelist={['*']}
          useWebKit={true}
          mixedContentMode="always"
          startInLoadingState={true}
          onLoadStart={(event) => { console.log('页面开始加载'); }}
          onLoadEnd={(event) => { console.log('页面加载结束'); }}
          onError={syntheticEvent => { console.error(syntheticEvent); }}
        />)
      }

    </View>
  );
};

const screenHeight = Dimensions.get('window').height;

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  ui_container: {
    alignItems: 'center'
  },
  ui_button: {
    width: 180,
    height: 60,
    position: 'absolute',
    zIndex: 2,
    justifyContent: 'center',
    alignItems: 'center',
    textAlign: 'center'
  },
  ui_start_button: {
    top: screenHeight * 0.35
  },
  ui_load_button: {
    top: screenHeight * 0.5
  }
});

export default App;